// diagram := `
// VVCCGG
// VVCCGG`

package kindergarten

import (
	"errors"
	"regexp"
	"sort"
	"strings"
)

const testVersion = 1

type Garden struct {
	plants   [2][]string
	children []string
}

var PLANTS = map[string]string{
	"R": "radishes",
	"C": "clover",
	"G": "grass",
	"V": "violets",
}

var plantReg = regexp.MustCompile(`[A-Z]`)

func NewGarden(diagram string, children []string) (g *Garden, err error) {
	t := strings.Split(diagram, "\n")
	if len(t) != 3 {
		err = errors.New("diagram wrong")
		return
	}

	p1 := plantReg.FindAllString(t[1], -1)
	p2 := plantReg.FindAllString(t[2], -1)

	if len(t[1]) != len(t[2]) ||
		len(p1) != len(t[1]) ||
		len(p1)%2 != 0 ||
		len(p2) != len(t[2]) ||
		len(p2)%2 != 0 {
		err = errors.New("diagram2 wrong")
		return
	}

	s := strings.Join(children, "_")
	for i := 0; i < len(children); i++ {
		if strings.Count(s, children[i]) > 1 {
			err = errors.New("duplicate name")
			return
		}
	}

	g = &Garden{}
	g.plants[0] = p1
	g.plants[1] = p2
	cpChild := make([]string, len(children))
	copy(cpChild, children)
	sort.Strings(cpChild)
	g.children = cpChild

	return
}

func (g *Garden) Plants(child string) (r []string, ok bool) {
	idx := -1
	for i := 0; i < len(g.children); i++ {
		if child == g.children[i] {
			idx = i * 2
		}
	}

	if -1 == idx {
		return
	}

	for i := 0; i < 2; i++ {
		n := g.plants[i][idx]
		r = append(r, PLANTS[n])
		n = g.plants[i][idx+1]
		r = append(r, PLANTS[n])
	}

	ok = true
	return
}
